# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'

import sys
sys.stdout = sys.stderr

import atexit, logging, cherrypy
from freya.commands import Freya
from ulise.commands import Ulise
from hermes.commands import Hermes
from configs import configs as conf

class Welcome(object):
    def welcome(self):
        return "Welcome to voda-services"

def setup_routes():
    d = cherrypy.dispatch.RoutesDispatcher()

#   index
    d.connect(name='welcome', route='/', controller=welcome, action='welcome', conditions=dict(method=['GET']))

#   freya
    d.connect(name='authorize', route='/freya/authorize', controller=freya, action='authorize', conditions=dict(method=['POST']))
    d.connect(name='authenticate', route='/freya/authenticate', controller=freya, action='authenticate', conditions=dict(method=['GET']))
    d.connect(name='change_password', route='/freya/change_password', controller=freya, action='change_password', conditions=dict(method=['POST']))
    d.connect(name='add_permissions', route='/freya/add_permissions', controller=freya, action='add_permissions', conditions=dict(method=['POST']))
    d.connect(name='remove_permissions', route='/freya/remove_permissions', controller=freya, action='remove_permissions', conditions=dict(method=['POST']))

#   ulise
    d.connect(name='post', route='/ulise/:leaderboard_name/:order/post', controller=ulise, action='post', conditions=dict(method=['POST']))
    d.connect(name='get_leaderboard', route='/ulise/:leaderboard_name/:order', controller=ulise, action='get_leaderboard', conditions=dict(method=['GET']))

#   hermes
    d.connect(name='send_message', route='/hermes/:credentials/send_message', controller=hermes, action='send_message', conditions=dict(method=['POST']))

    conf = {'/':
                {
                    'request.dispatch': d,
                    'tools.encode.on': True,
                    'tools.encode.encoding': 'utf-8',
                    'tools.CORS.on': True
                }
    }
    logging.info('Routes Dispatcher created')
    return conf


def CORS():
    response = cherrypy.response
    response.headers['Content-Type'] = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = '*'

welcome = Welcome()
ulise = Ulise()
freya = Freya()
hermes = Hermes()


def setup_server(mongo_host='127.0.0.1', mongo_port=27017):
    cherrypy.config.update({'environment':'embedded'})

    if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
        cherrypy.engine.start(blocking=False)
        atexit.register(cherrypy.engine.stop)

    conf.client = conf.create_connection(mongo_host, mongo_port)
    cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
    application = cherrypy.Application(None, script_name=None, config=setup_routes())

    return application